from collections import OrderedDict
import os


class LRUCache(object):

    def __init__(self, max_size, save_file=None):

        self.max_size = max_size

        self.linked_map = OrderedDict()

        self.save_file = save_file

    def set(self, key, value):

        if key in self.linked_map:

            self.linked_map.pop(key)

        if self.max_size == len(self.linked_map):

            self.linked_map.popitem(last=False)

        self.linked_map.update({key: value})

    def get(self, key):

        value = self.linked_map.get(key)

        if value:

            self.linked_map.pop(key)

            self.linked_map.update({key: value})

        return value

    def save(self):
        if self.save_file:
            with open(self.save_file, 'wt') as f:
                f.write(','.join([k+':'+v for k, v in self.linked_map.items()]))

    def load(self):
        if self.save_file and os.path.isfile(self.save_file):
            with open(self.save_file, 'rt') as f:
                data = f.read()
                for kv in data.split(','):
                    if kv is None:
                        continue
                    list_kv = kv.split(':')
                    k = list_kv[0]
                    if k is None:
                        continue
                    v = None
                    if len(list_kv) > 1:
                        v = list_kv[1]
                    self.set(k, v)

    def clear(self):
        self.linked_map.clear()

    def size(self):
        return len(self.linked_map)